package Server.Login.Model;

import Server.Login.View.*;
import Server.Login.Controller.*;
import Exception.LoginFailureException;

import java.io.*;

public class ServerLoginModel 
{
    public void initialize()
    {
    	initializeServerAccount();
    }
    public void initializeServerAccount()
    {
    	try
    	{
    	    BufferedReader in = new BufferedReader(new FileReader(this.ServerAccountConfigureFilePath));
    	    this.ServerAccount = in.readLine();
    	    this.ServerPassword = in.readLine();
    	}
    	catch(FileNotFoundException exception)
    	{
    		System.out.println("FileNotFound : " + this.ServerAccountConfigureFilePath);
    		exception.printStackTrace();
    	}
    	catch(IOException exception)
    	{
    		System.out.println("IOException happened when read file : " + this.ServerAccountConfigureFilePath);
    		exception.printStackTrace();
    	}
    }
    public void setViewAndController(ServerLoginView view, ServerLoginController controller)
    {
    	this.view = view;
    	this.controller = controller;
    }
    public boolean login(String userName, char[] password) throws LoginFailureException
    {
    	System.out.println("user : password " + new String(password));
    	System.out.println("password " + this.ServerPassword);

    	if (!userName.equals(this.ServerAccount))
    	{
    		throw new LoginFailureException(this.noAccountMessage);
    	}
    	else if (userName.equals(this.ServerAccount) && !new String(password).equals(this.ServerPassword))
    	{
            throw new LoginFailureException(this.passwordErrorMessage);
    	}
    	else if (userName.equals(this.ServerAccount) && new String(password).equals(this.ServerPassword))
    	{
    	    return true;
    	}
    	return true;
    }
    private ServerLoginView view;
    private ServerLoginController controller;
    private String ServerAccountConfigureFilePath = new String("c:\\server_user_password.txt");
    private String ServerAccount;
    private String ServerPassword;
    
    private String noAccountMessage = new String("No Such Account");
    private String passwordErrorMessage = new String("Password Error");
    private String loginSuccessfulMessage = new String("Login Successful");
}
